package com.orisper.utils;

import java.io.IOException;

import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import aos.framework.core.id.AOSId;
import aos.framework.core.utils.AOSCfgHandler;
import aos.framework.core.utils.AOSUtils;

/**
 * 文件上传类
 * 
 * @author DL
 *
 */
public class QiniuUploadFile {
	/**
	 * 七牛配置
	 */
	public static final String QN_accessKey  =AOSCfgHandler.getValue("qiniu_accessKey");
	public static final String QN_secretKey  =AOSCfgHandler.getValue("qiniu_secretKey");
	public static final String QN_bucket  = AOSCfgHandler.getValue("qiniu_bucket");
	public static final String QN_url  = AOSCfgHandler.getValue("qiniu_url");

	
	public static String upload(MultipartFile file) {
		String url = "";
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// ...生成上传凭证，然后准备上传
		String accessKey = QN_accessKey;
		String secretKey = QN_secretKey;
		String bucket = QN_bucket;// 七牛存储空间

		String originalFileName = file.getOriginalFilename();
		System.out.println("原始名称：" + originalFileName + "." + originalFileName.lastIndexOf("."));

		String fileType = file.getContentType();
		System.out.println("文件类型：" + fileType);
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = AOSUtils.getDateStr("yyyyMMdd")+"-"+AOSId.uuid() + "." + fileType.split("/")[1];
		System.out.println("指定的名称：" + key);
		// 将流转换成byte数组
		byte[] uploadBytes = null;
		try {
			uploadBytes = file.getBytes();
		} catch (IOException e) {
			e.printStackTrace();
			return url;
		}
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);// 获取上传Token
		try {
			Response response = uploadManager.put(uploadBytes, key, upToken);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
			url=QN_url+putRet.key;
			
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			
		}
		
		return url;

	}
}
